package com.yanfan.ibms.common.utils;

import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 签名生成工具类
 */
public class SignCreateUtils {

    // 将对象转换为按字典顺序排序的URL参数字符串

    /**
     * 将对象转换为按字典顺序排序的URL参数字符串
     * @param target map类型参数
     * @return
     */
    public static String objectToUrlParameters(Map<String, Object> target) {
        return new TreeMap<>(target).entrySet()
                .stream()
                .filter(entry -> entry.getValue() != null) // 跳过值为null的参数
                .map(entry -> entry.getKey() + "=" + encodeParameter(entry.getValue()))
                .collect(Collectors.joining("&"));
    }

    // 对参数进行URL编码
    private static String encodeParameter(Object value) {
        try {
            return URLEncoder.encode(value.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }

    // 生成MD5签名并转换为大写
    public static String MD5Sign(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            return Hex.encodeHexString(md.digest()).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     *  生成签名
     * @param bodyParams 传入的参数
     * @param anyString  需要拼接的字符串
     * @return
     */
    public static String generateSignature(Map<String, Object> bodyParams, String anyString) {
        // 将参数Map按字典顺序排序并转换为URL参数字符串
        String stringA = objectToUrlParameters(bodyParams);

        // 拼接key和字符串A生成新的字符串B
        String stringB =  stringA + "&newString=" + anyString;

        // 对字符串B进行MD5加密并转换为大写，得到签名
        return MD5Sign(stringB);
    }

    public static void main(String[] args) {
        String appid = "ddc";
        String parkingStr = "123";
        String nonceStr = "ssc";
        String signType = null;
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("parkingStr",parkingStr);
        map.put("nonceStr",nonceStr);
        map.put("signType",signType);
        String cddcsd = generateSignature(map, "cddcsd");
        System.out.println(cddcsd);
    }

}

